﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace BaseHelper.WinForm
{
    public class TreeNodeHelper
    {
        public static TreeNode GetTreeNodeByKey(TreeNode tv, string Key, bool IsFindChild = false, bool isMatch = true)
        {
            Regex reg = new Regex(Key);
            foreach (TreeNode tn in tv.Nodes)
            {
                if (isMatch)
                {
                    if (reg.Match(tn.Text).Success)
                        return tn;
                }
                else
                {
                    if (tn.Text.Equals(Key))
                        return tn;
                }
            }

            if (IsFindChild)
            {
                foreach (TreeNode tn in tv.Nodes)
                {
                    if (tn.Nodes.Count > 0)
                    {
                        TreeNode tnChild = GetTreeNodeByKey(tn, Key, IsFindChild, isMatch);
                        if (tnChild != null)
                            return tnChild;
                    }
                }
            }

            return null;
        }

        public static TreeNode GetTreeNodeByTag(TreeNode tv, string Tag, bool IsFindChild = false, bool isMatch = true)
        {
            Regex reg = new Regex(Tag);
            foreach (TreeNode tn in tv.Nodes)
            {
                if (isMatch)
                {
                    if (reg.Match(tn.Tag.ToString()).Success)
                        return tn;
                }
                else
                {
                    if (tn.Tag.ToString().Equals(Tag))
                        return tn;
                }
            }

            if (IsFindChild)
            {
                foreach (TreeNode tn in tv.Nodes)
                {
                    if (tn.Nodes.Count > 0)
                    {
                        TreeNode tnChild = GetTreeNodeByTag(tn, Tag, IsFindChild, isMatch);
                        if (tnChild != null)
                            return tnChild;
                    }
                }
            }

            return null;
        }
    }
}
